package com.lry.easyExcel.utils;

/**
 * @author JiangJie
 * @create 2020-11-27 16:04
 */
public class Crc16Utils {
    //=> 01 03 9D A5 00 08 7B 83
    public static void main(String[] args) {
        System.out.println(getCRC(ByteUtil.hexToByteArray("01039DA50008")));
    }

    public static String getCRC(byte[] bytes) {
        int CRC = 0x0000ffff;
        int POLYNOMIAL = 0x0000a001;

        int i, j;
        for (i = 0; i < bytes.length; i++) {
            CRC ^= ((int) bytes[i] & 0x000000ff);
            for (j = 0; j < 8; j++) {
                if ((CRC & 0x00000001) != 0) {
                    CRC >>= 1;
                    CRC ^= POLYNOMIAL;
                } else {
                    CRC >>= 1;
                }
            }
        }
        //高低位互换，输出符合相关工具对Modbus CRC16的运算
        CRC = ( (CRC & 0xFF00) >> 8) | ( (CRC & 0x00FF ) << 8);
        return Integer.toHexString(CRC);
    }

}
